import os
from IPython.external.qt_for_kernel import QtCore
from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QListWidgetItem
import sys
import qdarkgraystyle

import serial
import pandas as pd
import numpy as np
import time
from struct import *

ser = serial.Serial("COM2")


class Window(QMainWindow):
    sigCmd = pyqtSignal(str)
    sigPath = pyqtSignal(str)
    sigPosition = pyqtSignal(int)

    def __init__(self):
        super(Window, self).__init__()
        uic.loadUi("origin.ui", self)

        self.btnPlay.setEnabled(False)
        self.actionaddFile.triggered.connect(self.open_file)
        self.btnchooseColumn.clicked.connect(self.choose_columns)
        self.btnPlay.clicked.connect(self.play_chosen)

        self.playlist.clicked.connect(self.set_state)

        self.btnPrevious.clicked.connect(self.skip2previous)
        self.btnNext.clicked.connect(self.skip2next)

        self.state = "Play"
        self.playing = ""
        self.index = 0

        # 创建播放器线程
        self.thread = Player()

        # 关联与播放器线程通信用的信号与槽
        self.sigPath.connect(self.thread.path_slot)
        self.sigCmd.connect(self.thread.cmd_slot)
        self.thread.position_changed.connect(self.set_position)
        self.thread.start()

    def open_file(self):
        file_name = QFileDialog()
        file_name.setFileMode(QFileDialog.ExistingFiles)
        names = file_name.getOpenFileNames(self, "Open files", os.getenv("HOME"))
        self.myfile = names[0]
        self.playlist.addItems(self.myfile)

    def choose_columns(self):
        columnsInfile = ['DWJZ', 'LJJZ', 'JZZZL']
        for column in columnsInfile:
            item = QListWidgetItem(column)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
            item.setCheckState(QtCore.Qt.Unchecked)
            self.columnsList.addItem(item)

    def play_chosen(self):
        if self.state == "Play":
            self.state = "Pause"
            # self.btnplay.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
            filepath = self.playlist.currentItem().text()
            if filepath != self.playing:
                self.sigCmd.emit('stop')
                self.playing = filepath
                self.index = self.playlist.currentRow().__index__()
                self.slider.setRange(0, 1001)
                self.sigPath.emit(filepath)
                self.sigCmd.emit('play')
            else:
                self.sigCmd.emit('play')

        else:
            self.state = "Play"
            # self.btnplay.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
            self.sigCmd.emit('pause')

    def set_position(self, val):
        self.slider.setValue(val)

    def change_position(self):
        pass

    def skip2previous(self):
        self.state = "Play"
        self.playlist.setCurrentRow(self.index - 1)
        self.play_chosen()

    def skip2next(self):
        self.state = "Play"
        self.playlist.setCurrentRow(self.index + 1)
        self.play_chosen()

    def set_state(self):
        self.btnPlay.setEnabled(True)
        self.state = "Play"


class Player(QThread):
    position_changed = pyqtSignal(int)

    def __init__(self):
        super(Player, self).__init__()
        self.isPaused = True
        self.isToCancel = False
        self.filepath = ''
        self.i = 0
        # self.lstData = []

    def path_slot(self, path):
        self.filepath = path

    def cmd_slot(self, cmd):
        if cmd == 'play':
            self.isPaused = False
        elif cmd == 'pause':
            self.isPaused = True
        elif cmd == 'stop':
            self.isToCancel = True

    def run(self):
        while True:
            time.sleep(0.1)
            if self.filepath != '':
                df = pd.read_csv(self.filepath, usecols=[2, 3])
                mat = np.array(df)

            if not self.isPaused and self.i <= len(mat):
                data = pack("ffBBBB", *mat[self.i], 0x00, 0x00, 0x80, 0x7F)
                ser.write(data)
                self.position_changed.emit(self.i)
                time.sleep(0.1)
                self.i = self.i + 1

            if self.isToCancel:
                self.isToCancel = False
                self.i = 0


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkgraystyle.load_stylesheet())
    window = Window()
    window.show()
    sys.exit(app.exec())
